<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2015/8/11
 * Time: 16:49
 */
namespace Home\Controller;

use Think\Controller;
use Think\Log;

class OrderController extends Controller
{
    //订单的四个状态
    const PAY_WAIT = 0;//等待支付
    const PAY_SUCCESS = 1;//支付成功
    const PAY_FAIL = 2;//支付失败
    const PAY_TICKET_FAIL = 3;//出票失败

    const DEFAULT_LOAD_MORE_ORDER_COUNT = 5; //加载更多数量

    /**
     * 订单首页
     */
    public function index()
    {
        $numberOfOrder = 5;
        //把openId存到session中，给ajax方法用
        if (!isset($_SESSION['openId'])) {
            session("openId", getOpenId());
        }
        $this->assign("json", $this->getOrder(0, $numberOfOrder, self::PAY_WAIT));
        $this->display();
    }

    function more()
    {
        $type = intval(I("type"));
        $start = intval(I('start'));
        $json = $this->getOrder($start, self::DEFAULT_LOAD_MORE_ORDER_COUNT, $type);
        exit(json_encode($json));
    }

    /**
     * @param $start 开始下标
     * @param $numberOfOrder 数量
     * @param $orderType 订单类型
     * @return mixed
     */
    private function getOrder($start, $numberOfOrder, $orderType)
    {
        $openId = session("openId");
        $orderTable = M("order_info", "jt_");
        $schemaTable = M("schema_info", "jt_");
        //选取订单条件
        $condition = array();
        $condition['openid'] = $openId;
        //根据订单类型区别选取条件
        switch ($orderType) {
            case self::PAY_WAIT://待支付订单
                $condition['pay_status'] = self::PAY_WAIT;
                $condition['lockTime'] = array("exp", "> now()");//过期时间大于现在
                break;
            case self::PAY_SUCCESS://成功订单
                $condition['pay_status'] = self::PAY_SUCCESS;
                break;
            case self::PAY_FAIL://失败订单
                $condition['pay_status'] = array("exp", "in (0,2,3)");
                $condition['lockTime'] = array("exp", "<= now()");//过期时间小于现在
                break;
            case self::PAY_TICKET_FAIL:
                break;
        }
        $json['orders'] = $orderTable->where($condition)->field("orderID,schID,ticketAmt,create_time,lockTime")
            ->order("create_time desc")->limit($start, $numberOfOrder)->select();
        $json['count'] = count($json['orders']);//显示的订单数量
        //遍历获得的所有订单，根据订单的schId获取班次信息
        foreach ($json['orders'] as $key => $value) {
            $schID = $value['schid'];
            $schema = $schemaTable->where("schID='%s'", $schID)->field("Start_Station,End_Station,Sch_Date,Sch_Time")->find();
            $json['orders'][$key]['start_station'] = $schema['start_station'];
            $json['orders'][$key]['end_station'] = $schema['end_station'];
            $json['orders'][$key]['sch_date'] = $schema['sch_date'];
            $json['orders'][$key]['sch_time'] = $schema['sch_time'];
        }
        return $json;
    }

    /**
     * 搜索订单
     */
    public function search()
    {
        $this->display();
    }

    /**
     * 订单详情页面
     */
    public function detail()
    {
        $orderType = I("type");
        $orderId = I("orderId");
        $openId = getOpenId();
        //选取条件
        $condition = array();
        $condition['openid'] = $openId;
        $condition['orderId'] = $orderId;
        $which = "";//跳转至哪个页面
        $orderModel = null;
        switch($orderType){
            case self::PAY_WAIT:
                //重定向至Buy/pay
                $this -> redirect("Buy/pay",array("orderId" => $orderId,"referer" => "wait","openId" => $openId));
                /*$condition['pay_status'] = self::PAY_WAIT;
                $which = 'wait';
                $orderModel = M("order_info","jt_") -> where($condition) ->find();
                //todo 向微信提交订单
                $tools = getTools();
                $totalFee=1;
                $notifyUrl = "http://www.jsscom.com:9090/kyz/weChatPaymentServlet";
                $input = new \WxPayUnifiedOrder();
                $input->SetBody("车站购票");
                $input->SetAttach("车站购票");
                $input->SetOut_trade_no($orderId);
                $input->SetTotal_fee($totalFee);
                $input->SetTime_start(date("YmdHis"));
                $input->SetTime_expire(date("YmdHis", time() + 600));
                $input->SetGoods_tag("车站购票");
                $input->SetNotify_url($notifyUrl);
                $input->SetTrade_type("JSAPI");
                $input->SetOpenid($openId);
                $order = \WxPayApi::unifiedOrder($input);
                $jsApiParameters = $tools->GetJsApiParameters($order);
                $this -> assign("jsApiParameters",$jsApiParameters);*/
                //dump($order);
                //dump($jsApiParameters);
                break;
            case self::PAY_SUCCESS:
                $condition['pay_status'] = self::PAY_SUCCESS;
                $orderModel = M("order_info","jt_") -> where($condition) ->find();

                $which = 'succeed';
                break;
            case self::PAY_FAIL:
                $condition['pay_status'] = self::PAY_FAIL;
                $orderModel = M("order_info","jt_") -> where($condition) ->find();

                $which = 'fail';
                break;
        }
        $orderModel['number'] = strlen($orderModel['lockinfo']);//票张数
        $schemaModel = M("schema_info","jt_") -> where("SchID='%s'",$orderModel['schid']) -> find();
        $this -> assign("orderModel",$orderModel);
        $this -> assign("schemaModel",$schemaModel);
        //dump($orderModel);
        //dump($schemaModel);
        $this -> display($which);
    }

    /**
     * 取消锁票
     */
    public function ticketUnLock(){
        $orderId = I('orderId');
        $orderModel = M("order_info","jt_") -> where("orderID='%s'",$orderId) -> field("schID,ticketQty") -> find();

        if(!$orderModel){
            $this -> ajaxReturn(array("status" => "fail","msg" => "取消订单出错了!"));
        }

        $post_string = "cmd=TicketUnlock&args={param:{lockID:'".$orderId."',schID:'" .$orderModel['schid'] . "',ticketQty:'". $orderModel['ticketqty'] ."'}}";
        Log::write($post_string);
        $json = json_decode(post(C('REMOTE_INTERFACE_BASE_URL'), $post_string), true);
        if($json['errmsg'] == '成功'){
            $this -> ajaxReturn(array("status" => "success","msg" => "订单已取消"));
        } else{
            $this -> ajaxReturn(array("status" => "fail","msg" => "取消订单出错了!"));
        }
    }
}